package websocket

import (
	"math"
	"time"
)

type ServerOptions func(opt *serverOption)

const (
	defaultMaxConnectionIdle     = time.Duration(math.MaxInt64)
	defaultAckTimeOut            = time.Duration(30 * time.Second)
	defaultSendErrCount      int = 3
	defaultConcurrency       int = 10
)

type serverOption struct {
	Authentication
	ack             AckType
	ackTimeOut      time.Duration
	maxReSendCounts int
	pattern         string

	maxConnectionIdle time.Duration

	concurrency int

	discover Discover
}

func newServerOption(opts ...ServerOptions) serverOption {
	o := serverOption{
		maxConnectionIdle: defaultMaxConnectionIdle,
		Authentication:    new(authentication),
		pattern:           "/ws",
		ack:               NoAck,
		ackTimeOut:        defaultAckTimeOut,
		maxReSendCounts:   defaultSendErrCount,
		concurrency:       defaultConcurrency,
		discover:          &nopDiscover{},
	}

	for _, opt := range opts {
		opt(&o)
	}

	return o
}

func WithAuthentication(authentication Authentication) ServerOptions {
	return func(opt *serverOption) {
		opt.Authentication = authentication
	}
}

func WithServerDiscover(discover Discover) ServerOptions {
	return func(opt *serverOption) {
		opt.discover = discover
	}
}

func WithHandlerPatter(pattern string) ServerOptions {
	return func(opt *serverOption) {
		opt.pattern = pattern
	}
}

func WithMaxConnectionIdle(t time.Duration) ServerOptions {
	return func(opt *serverOption) {
		if t > 0 {

			opt.maxConnectionIdle = t
		}
	}
}

func WithAck(ack AckType, timeout time.Duration, maxReSendCounts int) ServerOptions {
	return func(opt *serverOption) {
		opt.ack = ack
		if timeout > 0 {
			opt.ackTimeOut = timeout
		}
		if maxReSendCounts > 0 {
			opt.maxReSendCounts = maxReSendCounts
		}

	}
}

func WithConcurrency(c int) ServerOptions {
	return func(opt *serverOption) {
		if c > 0 {

			opt.concurrency = c
		}
	}
}
